<script setup>
import {
  onMounted,
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  provide,
  nextTick
} from 'vue'
import { Dialog } from 'vant'
import { useRouter } from 'vue-router'

import {
  login,
  getInitParam,
  getAgentDetail,
  getAgentHistoryDetail,
  sessionLogDetail,
  tryAsking
} from '../../../service/api'
import { getUrlSearch } from '../../../utils/token'
import { jumpHttp, isWx, isIos } from '../../../utils/host'
import ChatBox from '../components/ChatBox.vue'
import Audios from '../components/Audios.vue'
import Worker from '../../../utils/worker.js?worker'
import agentIcon from '../../../assets/img/agent.png'
// import agentIcon from '../../../assets/img/school.png'
const router = useRouter()

const { appContext } = getCurrentInstance()
const proxy = appContext.config.globalProperties

const entityName = ref('')
const starRef = ref()
const innerRef = ref()
const voiceRef = ref()
const chatBoxRef = ref()
const sessionId = ref()
const showSuggested = ref(false)
const appid = ref()
const suggestArray = ref([])
const config = reactive({
  data: {},
  user: {}
})
const agentConfig = ref({})
// 播放声音
const playVoice = (voice) => {
  if (voiceRef.value) {
    voiceRef.value.voiceCallback(voice)
  }
}
// 语音或mp3结束
const voiceEnd = () => {
  chatBoxRef.value.voiceEnd()
}
// 设置静音
const muted = ref(true)
const toggleMuted = () => {
  muted.value = !muted.value
  voiceRef.value.toogleMuted(muted.value)
  if (!window.player) {
    chatBoxRef.value.initPlayer()
  }
}
const needPadding = ref(true)
// 方言切换
const showLanPop = ref(false)
const canChooseLan = ref(false)
const lans = [
  {
    text: '中文普通话',
    value: 'zwpth'
  },
  {
    text: '湖南话',
    value: 'hnh2'
  },
  {
    text: '河南话',
    value: 'hnh1'
  }
]

// 变量
const showForm = ref(false)
const formRef = ref(null)
const form = ref({})
const rules = ref()
const formItems = ref([])
const pickerVisible = reactive({}) // 控制每个弹出框的显示状态
const pickerValue = reactive({}) // 弹出框选中后的显示值
// 是否已填必填项
const requiredFiled = ref([])
const isFill = ref(false)
// 是否展示切换对话变量
const showUserInput = ref(false)
// 校验函数校验val是否为数字
const validatorMessage = (val) => {
  if (val === '') {
    return true
  } else if (!/^\d+$/.test(val)) {
    return '请输入数字'
  }
  return true
}

const onConfirmPicker = (e, key) => {
  // console.log(e, key)
  form.value[key] = e
  pickerValue[key] = e
  pickerVisible[key] = false
}

function onFailed(err) {
  isFill.value = false
  proxy.$toast('请填写必填项')
}
async function onSubmit() {
  isFill.value = true
  showForm.value = false
}
provide('isFill', isFill)
const getLanIndex = (value) => {
  let ret = ''
  lans.forEach((item, index) => {
    if (item.value === value) {
      ret = index
    }
  })
  return ret
}
const localLanIndex = getLanIndex(window.localStorage.getItem('lanText')) || 0
const lan = ref(lans[localLanIndex].value)
const onConfirmLan = (e) => {
  lan.value = e.value
  window.localStorage.setItem('lanText', e.value)
  proxy.$toast(`您选择了${e.text}`)
  showLanPop.value = false
}

// 获取智能体配置信息
async function getAgentInfo(agentId, isNew = false) {
  let res = ''
  if (agentId && agentId.startsWith('agent')) {
    agentId = agentId.replace('agent', '')
    try {
      res = await getAgentHistoryDetail(agentId, true)
    } catch (err) {
      console.log(err)
    }
    agentConfig.value = res
    appid.value = res?.installed_app_id
    document.title = entityName.value = res.name
    if (isNew) {
      await newChat()
    } else {
      getHistory()
    }
  } else {
    try {
      res = await getAgentDetail(agentId)
    } catch (err) {
      console.log(err)
    }
    agentConfig.value = res
    appid.value = res?.installed_app_id
    document.title = entityName.value = res.name
    await newChat()
  }

  // 是否展示建议问题
  let {
    suggested_questions_after_answer: { enabled = 0 }
  } = res?.model_config
  showSuggested.value = enabled
  // 变量表单相关
  let { user_input_form = [] } = res?.model_config
  showUserInput.value = user_input_form.length > 0
  formItems.value = user_input_form.map((ele) => {
    const [type, field] = Object.entries(ele)[0]
    const req = field.required ? '(必填)' : '(选填)'
    return {
      type,
      ...field,
      label: field.label + req,
      maxlength: field.max_length ? field.max_length : 48,
      placeholder:
        type === 'select' ? '请选择' + field.label : '请输入' + field.label
    }
  })
  // console.log('formItems.valueformItems.value', formItems.value)
  // 获取required为true的字段
  requiredFiled.value = formItems.value.filter((item) => item.required)
  isFill.value = requiredFiled.value <= 0
  form.value = formItems.value.reduce((pre, cur) => {
    pre[cur.variable] = null
    return pre
  }, {})
}

// 新的对话
async function newChat() {
  try {
    const res = await getInitParam({ appId: appid.value })
    config.data = res
    sessionId.value = res.sessionId // 会话id
    window.sessionStorage.setItem('sessionId', res.sessionId)
    proxy.$config = res
  } catch (err) {
    console.log(err)
  }
}

// 获取历史对话
async function getHistory() {
  const agentSessionId = window.sessionStorage.getItem('sessionId')
  sessionId.value = agentSessionId
  try {
    // 点击对话列表的对话详情sessionId
    const { records } = await sessionLogDetail(agentSessionId, true)
    const messages = []
    records[0].qaList.forEach((item) => {
      const obj = {
        showInfo: true,
        isHistory: true,
        isTextEnd: true,
        type: '',
        message: '',
        opsStatus: item.evaluate + '',
        uuid: item.uuid
      }
      if (item.type === 2) {
        obj.type = 'Bot'
      } else if (item.type === 1) {
        obj.type = 'User'
      }
      obj.message = item.content
        ? window.md.render(item.content).replaceAll('&lt;br&gt;', '<br />')
        : '当前问题没有回答'
      messages.push(obj)
    })
    if (messages.length > 0) {
      isFill.value = true
    }
    chatBoxRef.value.showMessages(messages)
  } catch (err) {
    console.log(err)
  }
}

provide('agentConfig', agentConfig)
provide('showSuggested', showSuggested)
provide('showForm', showForm)
provide('formData', form)
provide('showUserInput', showUserInput)

// 获取（试着问问）建议
async function _getTryAsking(params = {}) {
  const { data = [] } = await tryAsking(params)
  suggestArray.value = data
}
const catchNewMsgid = (e) => {
  if (showSuggested.value && e) {
    _getTryAsking({ msgid: e, appid: appid.value })
  }
}
provide('suggestArray', suggestArray)

const setHt = (p) => {
  if (p) {
    headerText.value.t1 = p.t1
    headerText.value.t2 = p.t2
    headerText.value.t3 = p.t3
  } else {
    headerText.value.t1 = '您好~'
    headerText.value.t2 = ''
    headerText.value.t3 = '有什么可以帮您的吗'
  }
}
provide('setHt', setHt)

const worker = new Worker()
worker.onmessage = (e) => {
  if (e.data === 'refresh') {
    login().then((res) => {
      window.access_token = res.access_token
    })
  }
}
// 对话记录
const addNewDialog = async () => {
  // 检测当前对话列表是否有用户的对话
  let hasUserType = false
  const cMsgs = chatBoxRef.value.messages
  const len = chatBoxRef.value.messages.length
  for (let i = 0; i < len; i++) {
    if (cMsgs[i].type === 'User') {
      hasUserType = true
      break
    }
  }
  if (hasUserType) {
    chatBoxRef.value.showMessages()
    // 清除用户表单，重新获取智能体配置信息
    const newAgentid = 'agent' + appid.value
    await getAgentInfo(newAgentid, true)
    // console.log(`output->清除用户表单，重新获取智能体配置信息`,newAgentid)
    // 清除对话建议
    suggestArray.value = []
    // 清除关联id
    chatBoxRef.value.startNewChat()
  } else {
    proxy.$toast('当前已在新对话中')
    return
  }
}

onMounted(async () => {
  window.access_token =
    window.sessionStorage.getItem('access_token') ||
    getUrlSearch(window.location.href, 'accessToken')
  if (!window.access_token) {
    proxy.$toast(
      '登录已过期，请重新登录',
      window.sessionStorage.getItem('access_token')
    )
    return
  }
  const agentId = getUrlSearch(window.location.href, 'id')
  await getAgentInfo(agentId)
  needPadding.value =
    getUrlSearch(window.location.href, 'NCPNavBarAlpha') === '0' && isWx()
})

onActivated(() => {
  if (window.sessionStorage.getItem('clickSearchItemFromSearchPage') === '1') {
    const sessionId = window.sessionStorage.getItem(
      'clickSearchItemFromSearchPageSession'
    )
    window.sessionStorage.removeItem('addNewFromSeachPage')
    window.sessionStorage.removeItem('clickSearchItemFromSearchPageSession')
  }
})
</script>
<template>
  <Audios v-if="sessionId" ref="voiceRef" @voice-end="voiceEnd" />
  <div class="appBg">
    <img src="../../../assets/img/bg.png" alt="" />
  </div>
  <div class="page-newindex" :class="{ padding: needPadding }">
    <div class="ops-box">
      <div class="ops left-ops">
        <img :src="agentConfig.icon ? agentConfig.icon : agentIcon" />
        <div>{{ agentConfig.name }}</div>
      </div>
      <div class="ops right-ops">
        <span class="new" @click="addNewDialog" />
        <!-- <span class="fankui" v-if="showKefu" @click="goKefu" /> -->
        <span
          class="language"
          v-if="canChooseLan"
          @click.stop="showLanPop = true"
        />
        <span class="voice" :class="{ muted: muted }" @click="toggleMuted" />
      </div>
    </div>
    <div class="chat-wraper small">
      <ChatBox
        ref="chatBoxRef"
        :muted="muted"
        :session-id="sessionId"
        :lan="lan"
        model=""
        v-if="sessionId"
        @play-voice="playVoice"
        @new-msgid="catchNewMsgid"
      />
    </div>
  </div>
  <van-popup
    id="lanpop"
    :show="showLanPop"
    position="bottom"
    round
    @click-overlay="showLanPop = false"
    @click-close-icon="showLanPop = false"
  >
    <van-picker
      :columns="lans"
      :default-index="localLanIndex"
      @cancel="showLanPop = false"
      @confirm="onConfirmLan"
    />
  </van-popup>
  <van-popup
    class="form-popup"
    :show="showForm"
    position="bottom"
    round
    @click-overlay="showForm = false"
  >
    <div class="form-title">
      <span>对话变量设置</span>
      <van-icon name="cross" @click="showForm = false" />
    </div>
    <van-form ref="formRef" @failed="onFailed" @submit="onSubmit">
      <div v-for="(item, index) in formItems" :key="index">
        <div v-if="item.type === 'text-input'">
          <div class="item-label" :class="{ required: item.required }">
            {{ item.label }}
          </div>
          <van-field
            v-model="form[item.variable]"
            :required="item.required"
            :maxlength="item.maxlength"
            :placeholder="item.placeholder"
            :name="item.variable"
            :rules="[{ required: item.required, message: item.placeholder }]"
          />
        </div>
        <div v-if="item.type === 'paragraph'" class="form-item">
          <div class="item-label" :class="{ required: item.required }">
            {{ item.label }}
          </div>
          <van-field
            v-model="form[item.variable]"
            :required="item.required"
            :maxlength="item.maxlength"
            :placeholder="item.placeholder"
            :name="item.variable"
            :rules="[{ required: item.required, message: item.placeholder }]"
            type="textarea"
            rows="2"
          />
        </div>
        <div v-if="item.type === 'select'">
          <div class="item-label" :class="{ required: item.required }">
            {{ item.label }}
          </div>
          <van-field
            v-model="form[item.variable]"
            :required="item.required"
            :placeholder="item.placeholder"
            :name="item.variable"
            :rules="[{ required: item.required, message: item.placeholder }]"
            @click="pickerVisible[item.variable] = true"
            is-link
            readonly
          />
          <van-popup
            v-model:show="pickerVisible[item.variable]"
            round
            position="bottom"
          >
            <van-picker
              :columns="item.options"
              @cancel="pickerVisible[item.variable] = false"
              @confirm="onConfirmPicker($event, item.variable)"
            />
          </van-popup>
        </div>
        <div v-if="item.type === 'number'">
          <div class="item-label" :class="{ required: item.required }">
            {{ item.label }}
          </div>
          <van-field
            v-model="form[item.variable]"
            :required="item.required"
            :placeholder="item.placeholder"
            :name="item.variable"
            :rules="[
              { required: item.required, message: item.placeholder },
              { validator: validatorMessage }
            ]"
          />
        </div>
      </div>
      <div style="text-align: center; width: 80%; margin: 0 auto">
        <div class="submit-btn">
          <van-button round block type="primary" native-type="submit"
            >提交</van-button
          >
        </div>
      </div>
    </van-form>
  </van-popup>
</template>

<style lang="less">
.appBg {
  position: absolute;
  width: 100%;
  height: 100%;
  img {
    display: block;
    width: 100%;
    height: 100%;
  }
}
.form-popup {
  background-color: #f7f8fa;
  max-height: 80%;
  .form-title {
    position: sticky;
    background-color: #f7f8fa;
    top: 0;
    z-index: 100;
    line-height: 0.4rem;
    height: 0.4rem;
    font-weight: bold;
    font-size: 0.32rem;
    color: #323233;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.6rem 0.32rem;
  }
  .required::before {
    font-size: 0.28rem;
    content: '*';
    color: #ff0000;
    margin-right: 4px;
  }
  .van-form {
    padding: 0 0.32rem;
    padding-bottom: 2rem;
  }
  .submit-btn {
    position: fixed;
    bottom: 0;
    padding: 0.2rem 1rem;
    background-color: #f7f8fa;
    left: 50%;
    width: 100%;
    transform: translateX(-50%);
    z-index: 100;
  }
  .item-label {
    padding: 0.2rem 0;
    font-size: 0.28rem;
  }
}

.page-newindex {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 0.32rem 0 0;
  .ops-box {
    height: 0.56rem;
    margin-bottom: 0.2rem;
    padding: 0 0.32rem;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .ops {
      display: flex;
    }
    span {
      width: 0.56rem;
      height: 0.56rem;
    }
    .left-ops {
      font-size: 0.34rem;
      font-weight: bold;
      display: flex;
      align-items: center;
      img {
        width: 0.8rem;
        height: 0.8rem;
        border-radius: 50%;
        border: 1px solid #c4d2fe;
        margin-right: 0.2rem;
      }
    }
    .right-ops {
      flex-direction: row-reverse;
      span {
        margin-left: 0.15rem;
        &:last-child {
          margin-left: 0;
        }
      }
      .new {
        background-image: url('../../../assets/img/new-dialog.png');
        background-size: 100% 100%;
        border-radius: 50%;
      }
      .voice {
        background-image: url('../../../assets/img/voice1.png');
        background-size: 100% 100%;
      }
      .muted {
        background-image: url('../../../assets/img/voice0.png');
        background-size: 100% 100%;
      }
      .language {
        background-image: url('../../../assets/img/lan.png');
        background-size: 100% 100%;
      }
      .fankui {
        background-image: url('../../../assets/img/kefu.png');
        background-size: 100% 100%;
      }
    }
  }
  .header {
    width: 100%;
    height: 3.2rem;
    position: relative;
    padding: 0 0.32rem;
    #digit {
      width: 100%;
      height: 3.2rem;
      margin: 0 auto;
      overflow: hidden;
      background-color: rgba(255, 255, 255, 0);
      transform-origin: 50% 0;
    }
    #digit.small {
      width: 3.2rem;
      height: 3.2rem;
      background-image: url('../../../assets/img/s-bg.png');
      background-size: 100% 100%;
    }
    #imageModel {
      width: 3.2rem;
      height: 3.2rem;
      overflow: hidden;
      margin: 0 auto;
    }
    #imageModel.small {
      width: 3.2rem;
      height: 3.2rem;
      background-image: url('../../../assets/img/s-bg.png');
      background-size: 100% 100%;
    }
    .infos {
      position: absolute;
      top: 0;
      left: 1.6rem;
      width: 4rem;
      height: 1.5rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-left: 0.4rem;
      font-size: 0.3rem;
      opacity: 0;
      font-weight: bold;
      font-weight: 600;
      color: #333;
    }
  }
  .chat-wraper {
    width: 100%;
    flex: 1;
    z-index: 99;
    position: relative;
    padding: 0.2rem 0.32rem 0;
    &.hasBg {
      background: linear-gradient(180deg, #d1f3ff 0%, #dcf5fd 100%);
    }
    &.small.hasBg {
      background: transparent;
    }
  }
}
</style>
